package org.springframework.web.servlet.view.excel;

import com.monkey.core.plugin.report.excel.ExcelData;
import com.monkey.core.plugin.report.excel.ExcelFiller;
import com.monkey.core.plugin.report.excel.ExcelTemplate;
import com.monkey.utils.WebUtils;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.view.document.AbstractExcelView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Map;
import java.util.Set;

/**
 * <p/>
 * 使用方式：
 * 1.配置 {@link org.springframework.web.servlet.view.ReportViewResolver},controller中返回excel模板的路径，添加excel:  eg:"excel:excel/excel-report"
 * 2.在controller中直接返回{@link com.monkey.core.plugin.report.excel.ExcelData}对象，在ExcelData中设置templatePath
 * </P>
 * <p/>
 * Created by silentwu on 2015/6/26.
 */
public class AppExcelView extends AbstractExcelView {


    /**
     * excel 的数据对象  ExcelData放到model中的key
     */
    public static final String EXCEL_DATA_MODEL_KEY = AppExcelView.class + "_ExcelData";

    public AppExcelView() {
    }

    @Override
    public void render(Map<String, ?> model, HttpServletRequest request, HttpServletResponse response) throws Exception {
        ExcelData excelData = loadExcelData(model);
        String templatePath = excelData.getTemplatePath();
        if (StringUtils.hasText(templatePath)) {
            setUrl(templatePath);
        }
        super.render(model, request, response);
    }

    @Override
    protected void buildExcelDocument(Map<String, Object> model, HSSFWorkbook workbook, HttpServletRequest request, HttpServletResponse response) throws Exception {
        ExcelData excelData = loadExcelData(model);

        String downloadFileName = WebUtils.encodeChineseDownloadFileName(request, excelData.getDownloadFileName());
        response.setHeader("Content-Disposition", "attachment; filename=" + downloadFileName + ";");

        ExcelFiller excelFiller = new ExcelFiller(new ExcelTemplate(workbook), excelData);
        excelFiller.fill();
    }

    private ExcelData loadExcelData(Map<String, ?> model) {
        ExcelData excelData = (ExcelData) model.get(EXCEL_DATA_MODEL_KEY);
        if (excelData == null) {
            Set<String> keys = model.keySet();
            for (String key : keys) {
                Object value = model.get(key);
                if (value instanceof ExcelData) {
                    excelData = (ExcelData) value;
                }
            }
        }
        return excelData;
    }

}
